package controller

import (
	"crypto/md5"
	"fmt"
	"gin-epg/internal/app/common/middleware"
	"gin-epg/internal/app/common/rsp"
	"gin-epg/internal/app/entity"
	"gin-epg/internal/app/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

// RestResponse 响应结构体
type RestResponse struct {
	Status  int         `json:"status"`
	Result  interface{} `json:"result,omitempty"`
	Message string      `json:"message,omitempty"`
}

// LoginData 登录数据结构体
type LoginData struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// UserInfo 用户信息结构体
type UserInfo struct {
	Token string       `json:"token"`
	User  *entity.User `json:"user"`
}

// doLogin 登录处理函数
func DoLogin(c *gin.Context) {
	var loginData LoginData
	if err := c.ShouldBindJSON(&loginData); err != nil {
		c.JSON(http.StatusBadRequest, RestResponse{Status: 400, Message: "请求参数错误"})
		return
	}

	username := loginData.Username
	password := loginData.Password

	loginUser, err := service.FindUserByName(username)
	if err != nil || loginUser == nil {
		c.JSON(http.StatusUnauthorized, RestResponse{Status: 401, Message: "用户不存在"})
		return
	}

	dbPassword := loginUser.Password
	encryptedText := MD5(password)

	if dbPassword != encryptedText {
		c.JSON(http.StatusUnauthorized, RestResponse{Status: 401, Message: "登录失败"})
		return
	}

	userInfoClaims := map[string]interface{}{
		"id":        loginUser.ID,
		"username":  loginUser.Username,
		"role":      "user",
		"avatarUrl": loginUser.AvatarURL,
	}

	token, err := middleware.GenerateToken(userInfoClaims)
	if err != nil {
		rsp.Error(c, "生成Token失败")
		return
	}

	userInfo := UserInfo{
		Token: token,
		User:  loginUser,
	}
	rsp.Success(c, "登录成功", userInfo)
}

func Logout(c *gin.Context) {
	//取出header的token
	token := c.Request.Header.Get("token")
	middleware.DeleteToken(token)
	rsp.Success(c, "退出成功", nil)
}

func MD5(str string) string {
	data := []byte(str) //切片
	has := md5.Sum(data)
	md5str := fmt.Sprintf("%x", has) //将[]byte转成16进制
	return md5str
}
